<template>
  <div class="main">
    <div class="title">已接订单列表</div>
    <div class="btn-group">
      <div class="search">
        <div class="search-item mr10">
          <div class="label">领单时间：</div>
          <div class="value">
            <el-config-provider :locale="zhCn">
              <el-date-picker
                v-model="create_time"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
              </el-date-picker>
            </el-config-provider>
          </div>
          
        </div>
        <div class="search-item mr10">
          <div class="label">状态：</div>
          <div class="value">
            <el-select v-model="status" placeholder="请选择">
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          
        </div>
        <div class="search-item">
          <el-button class="check-btn" type="primary" :loading="refreshLoading" @click="getOrderList"
            >查询</el-button
          >
        </div>
      </div>
      
      
    </div>
    
    <div class="content">
      <el-table :data="orderList" style="width: 100%" border stripe>
        <el-table-column prop="user_order_id" label="订单ID">
          <template #default="scope">
            <div class="flex">
              <span class="mr10">{{ scope.row.user_order_id }}</span>
              <el-icon @click="copyText(scope.row.user_order_id)"
                ><CopyDocument
              /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="user_order_id" label="手机号">
          <template #default="scope">
            <div class="flex">
              <span class="mr10">{{ scope.row.target }}</span>
              <el-icon @click="copyText(scope.row.target)"
                ><CopyDocument
              /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="target_desc" label="规格"></el-table-column>
        <el-table-column prop="status_name" label="状态">
          <template #default="scope">
            <div class="flex">
              <span class="mr10">{{ scope.row.status_name }}</span>
              <el-icon  @click="getOrderStatus(scope.row)"
                ><Refresh
              /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="rsp_info" label="备注">
          <template #default="scope">
            {{ scope.row.rsp_info ? scope.row.rsp_info : '--' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="create_time"
          label="领单时间"
          :formatter="formatterCreateTime"
        >
        </el-table-column>
        <!-- <el-table-column label="充值状态">
          <template #default="scope">
            {{ scope.row.userStatus ? scope.row.userStatus : '--' }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="充值凭证">
          <template #default="scope">
            {{ scope.row.voucher }}
            <div v-if="scope.row.voucher">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.voucher"
                fit="cover"
              />
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button
              @click="updateOrder(scope.row)"
              size="small"
              type="success"
              v-if="scope.row.status ===999"
              >上传凭证</el-button
            >
            <el-button
              @click="showPayImage(scope.row)"
              size="small"
              type="primary"
              :disabled="!scope.row.voucher"
              v-if="scope.row.status === 8 || scope.row.status === 9"
              >查看凭证</el-button
            >
            <el-button
                @click="deleteOrder(scope.row)"
                size="small"
                type="danger"
                >删除</el-button
              >
          </template>
        </el-table-column>
      </el-table>
      
    </div>
    <div class="tip" v-if="orderList.length">共{{ orderList.length }}条</div>
    <el-dialog
      title="接单"
      v-model="uploadResultDialogVisible"
      width="60%"
      center
    >
      <div class="upload-dialog-content">
        <el-form
          :model="resultForm"
          label-width="auto"
          style="max-width: 600px"
          ref="formRef"
        >
          <el-form-item
            label="请选择充值结果"
            prop="status"
            :rules="[
              {
                required: true,
                message: '请选择充值结果',
                trigger: 'change'
              }
            ]"
          >
            <el-select v-model="resultForm.status" placeholder="请选择">
              <el-option
                v-for="item in statusOptions2"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="请上传充值凭证"
            prop="voucher"
            :rules="[
              {
                required: true,
                message: '请上传充值凭证',
                trigger: 'change'
              }
            ]"
          >
            <el-upload
              ref="uploadRef"
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :limit="1"
              :on-exceed="uploadExceed"
              :on-change="uploadChange"
              accept="image/*"
            >
              <el-icon><Plus /></el-icon>

              <template #file="{ file }">
                <div>
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url"
                    alt=""
                  />
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-delete"
                      @click="removeUpload(file)"
                    >
                      <el-icon><Delete /></el-icon>
                    </span>
                  </span>
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadResultDialogVisible = false"
            >取 消</el-button
          >
          <el-button
            type="primary"
            :loading="uploadResultLoading"
            @click="submitUploadResult"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <el-image-viewer @close="hideImageViewer" v-if="imgViewerVisible" :url-list="imgViewList" />
  </div>
</template>
<script setup>
import { timestampToTime, fileToBase64,getTodayStr } from '@/utils/tools'
import { request } from '@/api/fetch'
import { onMounted, reactive } from 'vue'
import { ElMessage,ElMessageBox  } from 'element-plus'
import { CopyDocument, Delete, Plus,Refresh } from '@element-plus/icons-vue'
import { genFileId } from 'element-plus'
import 'dayjs/locale/zh-cn'
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
const imgViewerVisible = ref(false)
const imgViewList = ref([])
const refreshLoading = ref(false)
const orderList = ref([])
const status = ref(999)
const create_time = ref('')
const statusOptions = ref([
  {
    label: '处理中',
    value: 999
  },
  {
    label: '充值成功',
    value: 9
  },
  {
    label: '充值失败',
    value: 8
  },
  {
    label: '全部',
    value: ''
  }
])
const statusOptions2 = ref([
  {
    label: '成功',
    value: 9
  },
  {
    label: '失败',
    value: 8
  }
])
const resultForm = reactive({
  user_order_id: '', // 订单id
  status: '', // 订单状态
  voucher: '' // 凭证图片
})
const uploadResultDialogVisible = ref(false)
const uploadResultLoading = ref(false)

const uploadRef = ref()
const formRef = ref()

function resetResultForm() {
  resultForm.user_order_id = ''
  resultForm.status = ''
  resultForm.voucher = ''
  
  removeUpload()
  if(formRef.value){
    formRef.value.clearValidate()
  }
}
async function getOrderStatus(row){
  let user_order_id = row.user_order_id
  let data = await request('/queryBeeOrder?user_order_id='+user_order_id)
  if(data.status !== row.status){
    getOrderList()
    ElMessage({
      type:'success',
      message:'状态已更新',
      
    })
  }else {
    ElMessage({
      message:'状态已是最新，不需要更新',
      type: 'warning',
      plain: true,
    })
  }

}

function deleteOrder(row){
  ElMessageBox.confirm(
    '删除后无法恢复，确定要删除该订单吗？',
    '提示',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async ()=>{
      try {
        await request('/deleteSelfOrder', {
          method: 'POST',
          body: {
            user_order_id: row.user_order_id
          }
        })
        setTimeout(() => {
          getOrderList()
        }, 0)
      } catch (error) {
        
      } finally{
        ElMessage({
          type: 'success',
          message: '删除成功，订单列表已刷新',
        })
      }
    
  })
}

function updateOrder(row) {
  resetResultForm()
  resultForm.user_order_id = row.user_order_id
  uploadResultDialogVisible.value = true
}

function removeUpload(file) {
  if(uploadRef.value){
    uploadRef.value.clearFiles()
  }
  
}
function uploadExceed(files) {
  uploadRef.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  uploadRef.value.handleStart(file)
}

async function uploadChange(file) {
  console.log('uploadChange:', file)
  let fileRaw = file.raw
  fileToBase64(fileRaw, (baseStr) => {
    resultForm.voucher = baseStr
  })
}

async function copyText(text) {
  await navigator.clipboard.writeText(text)
  ElMessage({
    type: 'success',
    message: '复制成功'
  })
}
function submitUploadResult() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (!resultForm.user_order_id) {
        ElMessage({
          type: 'error',
          message: '订单号不能为空'
        })
        return
      }
      if (!resultForm.status) {
        ElMessage({
          type: 'error',
          message: '请选择充值结果'
        })
        return
      }
      if (!resultForm.voucher) {
        ElMessage({
          type: 'error',
          message: '请选择上传充值凭证'
        })
        return
      }
      // 提交充值结果

      uploadResultLoading.value = true
      try {
        await request('/updateBeeOrder', {
          method: 'POST',
          body: {
            data: JSON.stringify(resultForm)
          }
        })
        ElMessage({
          type: 'success',
          message: '上传成功，订单列表已刷新'
        })
        resetResultForm()
        
        setTimeout(() => {
          getOrderList()
        }, 0)
      } catch (error) {
        
      } finally{
        uploadResultDialogVisible.value = false
        uploadResultLoading.value = false
      }
      
      
    }
  })
}
function hideImageViewer(){
  imgViewerVisible.value = false
}
function showPayImage(row) {
  imgViewerVisible.value = true
  imgViewList.value = [row.voucher]
}
function formatterCreateTime(row) {
  return timestampToTime(row.create_time * 1000)
}
async function getOrderList() {
  refreshLoading.value = true
  try {
    let data = await request('/getSelfOrder?status=' + status.value+'&create_time='+(create_time.value || ''))
    orderList.value = data
  } catch (error) {
  } finally {
    refreshLoading.value = false
  }
}
onMounted(() => {
  getOrderList()
})
</script>
<style lang="scss" scoped>
.btn-group{
  .check-btn{
    width: 100px;
  }
}
.search {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: flex-end;
  .search-item {
    display: flex;
    align-items: center;
    flex-shrink: 0;
    margin-top:10px;
    justify-content: flex-start;
    
    .label {
      flex-shrink: 0;
    }
    .value{
      flex-shrink: 0;
      :deep(.el-date-editor){
        .el-input__wrapper{
          width:inherit;
          box-sizing: border-box;
        }
      }
    }
  }
}
.tip{
  margin: 20px 0px;
  text-align: right;
  color:999;
}
</style>
